package com.itboye.ihomebank.widget.photo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.home.ActivityRenZheng;
import com.itboye.ihomebank.activity.home.ActivityFaBuHouse;
import com.itboye.ihomebank.activity.myzhujia.ActivityJvJiaRepair;
import com.itboye.ihomebank.widget.photo.ImageGridAdapter.TextCallback;
import com.itboye.ihomebank.util.ByAlert;

/**
 * 选择照片
 * 
 */
public class CopyOfImageGridActivity extends Activity {
	public static final String EXTRA_IMAGE_LIST = "imagelist";

	// ArrayList<Entity> dataList;//鐢ㄦ潵瑁呰浇鏁版嵁婧愮殑鍒楄〃
	List<ImageItem> dataList;
	GridView gridView;
	ImageGridAdapter adapter;// 鑷畾涔夌殑閫傞厤鍣�
	AlbumHelper helper;
	Button bt;
	TextView cancel;
	int maxCount;
	int type;
    HashMap<Integer,String> map =new HashMap<>();
	String	picture_name;
	String	fileName;
    private int num=0;//次数

	List<Uri> list=new ArrayList<>();
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				Toast.makeText(CopyOfImageGridActivity.this, "最多选择9张图片", 400)
						.show();
				break;
				case 1:
					Bundle data = msg.getData();
					String anInt = data.getString("int");
					Uri mUri1=getTempUri(list.size());
					Log.d("size====",anInt);
					Log.d("size====",mUri1.toString());
					map.put(list.size(),mUri1.toString());
					crop(Uri.parse(anInt),list.size());

					break;
				case 2:
					Bundle data1 = msg.getData();
					String anInt1 = data1.getString("int");
					Uri mUri2=getTempUri(list.size());
					map.put(list.size(),mUri2.toString());
					Log.d("size====",anInt1);
					Log.d("size====",mUri2.toString());
					crop(Uri.parse(anInt1),list.size());
					break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_image_grid);
		type = getIntent().getIntExtra("type", 1);
		maxCount=getIntent().getIntExtra("max", maxCount);
		helper = AlbumHelper.getHelper();
		helper.init(getApplicationContext());

		dataList = (List<ImageItem>) getIntent().getSerializableExtra(
				EXTRA_IMAGE_LIST);

		initView();
		bt = (Button) findViewById(R.id.bt);
		bt.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				ArrayList<String> list = new ArrayList<String>();
				Collection<String> c = adapter.map.values();
				Iterator<String> it = c.iterator();
				for (; it.hasNext();) {
					list.add(it.next());
				}
				if(list.size()>maxCount){
					ByAlert.alert("最多选择"+maxCount+"张图片");
					return;
				}
				//
				// if (Bimp.act_bool) {
				// // Intent intent = new Intent(ImageGridActivity.this,
				// // ActivityFaBuHouse.class);
				// // startActivity(intent);
				// finish();
				// Bimp.act_bool = false;
				// }
				for (int i = 0; i < list.size(); i++) {
					if (type == 1) {
						ActivityRenZheng.listImg.add(list.get(i));
					} else if (type == 2) {
						ActivityRenZheng.listImg2.add(list.get(i));
					} else if (type == 3) {
						//ActivityRenZheng.listImg3.add(list.get(i));
					}else if (type == 4) {
//						Message message = new Message();
//						Bundle bundle = new Bundle();
//						bundle.putString("int","file://"+list.get(i));
//						message.setData(bundle);
//						if (i==list.size()-1){
//							message.what=2;
//							mHandler.sendMessage(message);
//						}else {
//							message.what=1;
//							mHandler.sendMessage(message);
//						}
						ActivityFaBuHouse.listImg.add(list.get(i));
					}else if (type == 5) {
						ActivityJvJiaRepair.listImg.add(list.get(i));
					}
				}
				finish();
//				if (type!=4){
//					finish();
//				}

			}

		});
	}

	//剪切图片并保存
/*
     * 剪切图片
     */
	private  void  crop(Uri uri,int i) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 4);
		intent.putExtra("aspectY", 3);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 120);
		intent.putExtra("outputY", 90);
		list.add(Uri.parse(map.get(i)));
		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.parse(map.get(i)));
		Log.d("size====",Uri.parse(map.get(i))+"");

		intent .putExtra("scale", true);//黑边
		intent .putExtra("scaleUpIfNeeded", true);//黑边
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		Log.d("size====",i+"");
		startActivityForResult(intent, i);
	}

	@Override
	protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

	    if (requestCode<list.size()){
	    	num++;
			if (data == null) {
				return;
			}
			final Bundle extras = data.getExtras();
			if (extras != null) {
				processPhotoUpdate(list.get(requestCode),requestCode);
			}
		}
		if (num>=list.size()){
			Log.d("size====",list.size()+"");
			list.clear();
			num=0;
			finish();
		}



	}

	private void processPhotoUpdate(Uri uri,int i) {

//		Bitmap bitmap = BitmapFactory.decodeFile(tempFile.getAbsolutePath());// 获取相机返回的数据，并转换为Bitmap图片格式
// 读取uri所在的图片
		picture_name = android.text.format.DateFormat.format(
				"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
				+""+i+".jpg";
		Bitmap bitmap = null;
		FileOutputStream b = null;
		File file = new File("/sdcard/Image/");
		file.mkdirs();// 创建文件夹
		fileName = "/sdcard/Image/" + picture_name;
		try {
			bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
			if (bitmap!=null&&bitmap.getByteCount()>0){
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				ActivityFaBuHouse.listImg.add(fileName);
			}
		} catch (IOException e) {
			e.printStackTrace();
	    } finally {
		    try {
		    	if (b!=null){
					b.flush();
					b.close();
				}
		       } catch (IOException e) {
			      e.printStackTrace();
		       }
	}
		// SavePicInLocal(bitmap);

		Log.d("filename",fileName);
	}

	//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//
//
//		}




	private  Uri getTempUri(int i) {
		Log.d("size====", "121=");
		if (isSDCARDMounted()) {
//
			File f = new File(Environment.getExternalStorageDirectory(),
					android.text.format.DateFormat.format(
							"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
							+ ""+i+".jpg");
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Toast.makeText(CopyOfImageGridActivity.this, "getTempFile失败", Toast.LENGTH_LONG)
						.show();
			}
		return 	Uri.fromFile(f);

		} else {
			return null;
		}

	}

	private String optionBitmap(String path){
		if (!path.equals("")){

			// 设置参数
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true; // 只获取图片的大小信息，而不是将整张图片载入在内存中，避免内存溢出
			BitmapFactory.decodeFile("file://"+path, options);
			int height = options.outHeight;
			int width= options.outWidth;
			int inSampleSize = 2; // 默认像素压缩比例，压缩为原图的1/2
			int minLen = Math.min(height, width); // 原图的最小边长
			if(minLen > 100) { // 如果原始图像的最小边长大于100dp（此处单位我认为是dp，而非px）
				float ratio = (float)minLen / 100.0f; // 计算像素压缩比例
				inSampleSize = (int)ratio;
			}
			options.inJustDecodeBounds = false; // 计算好压缩比例后，这次可以去加载原图了
			options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例
			Bitmap bm = BitmapFactory.decodeFile("file://"+path, options); // 解码文件
			Log.w("TAG", "size: " + bm.getByteCount() + " width: " + bm.getWidth() + " heigth:" + bm.getHeight()); // 输出图像数据
		}
		return null;
	}
	private File getTempFile() {
		if (isSDCARDMounted()) {
//
			File f = new File(Environment.getExternalStorageDirectory(),
					android.text.format.DateFormat.format(
							"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
							+ ".jpg");
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Toast.makeText(CopyOfImageGridActivity.this, "getTempFile失败", Toast.LENGTH_LONG)
						.show();
			}
			return f;
		} else {
			return null;
		}
//			picture_name = android.text.format.DateFormat.format(
//					"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
//					+ ".jpg";
//			// SavePicInLocal(bitmap);
//			FileOutputStream b = null;
//			File file = new File("/sdcard/Image/");
//			file.mkdirs();// 创建文件夹
//			fileName = "/sdcard/Image/" + picture_name;
//			Bitmap bitmap = BitmapFactory.decodeFile("file://" +fileName);
//			try {
//				b = new FileOutputStream(fileName);
//				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} finally {
//				try {
//					b.flush();
//					b.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			return new File("file://" +fileName);
//		}else {
//			return null;
//		}
	}

	private boolean isSDCARDMounted() {
		String status = Environment.getExternalStorageState();

		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;
		return false;
	}

	/**
	 * 鍒濆鍖杤iew瑙嗗浘
	 */
	private void initView() {
		gridView = (GridView) findViewById(R.id.gridview);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		cancel = (TextView) findViewById(R.id.cancel);
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		adapter = new ImageGridAdapter(CopyOfImageGridActivity.this, dataList,
				mHandler);
		gridView.setAdapter(adapter);
		adapter.setTextCallback(new TextCallback() {
			public void onListen(int count) {
				bt.setText("完成" + "(" + count + ")");
			}
		});

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				/**
				 * 鏍规嵁position鍙傛暟锛屽彲浠ヨ幏寰楄窡GridView鐨勫瓙View鐩哥粦瀹氱殑瀹炰綋绫伙紝鐒跺悗鏍规嵁瀹冪殑isSelected鐘舵
				 * �锛� 鏉ュ垽鏂槸鍚︽樉绀洪�涓晥鏋溿� 鑷充簬閫変腑鏁堟灉鐨勮鍒欙紝涓嬮潰閫傞厤鍣ㄧ殑浠ｇ爜涓細鏈夎鏄�
				 */
				// if(dataList.get(position).isSelected()){
				// dataList.get(position).setSelected(false);
				// }else{
				// dataList.get(position).setSelected(true);
				// }
				/**
				 * 閫氱煡閫傞厤鍣紝缁戝畾鐨勬暟鎹彂鐢熶簡鏀瑰彉锛屽簲褰撳埛鏂拌鍥�
				 */
				// adapter.notifyDataSetChanged();
			}

		});

	}
}
